iT邦幫忙

0

[JavaScript學習筆記] - 數字與字串互相轉型別之方式

  • 分享至 

  • xImage
  •  

字串轉數字

let a = "1";
console.log(a+1);
//輸出11

加入parseInt語法

let a = "1";
a = parseInt(a); //將字串轉成數字,重新賦予新的值
console.log(a+1);
//輸出2

當 parseInt()括號內不是數字,會顯示NaN

a = parseInt("你好");
console.log(a);
//輸出NaN

小提醒:Input的文字欄位中的數字都會轉成字串,如果去取出就需要加入parseInt()語法去做轉型,轉型成數字

數字轉字串

let b = 1;
console.log(b+1);
//輸出2

加入toString()

let b = 1;
b = b.toString(); //自動轉成字串型別
console.log(typeof b); // 輸出string
console.log(b+1);
//輸出11

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言